package com.innovation.chengzhangriji.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.http.AllBabyResponse;
import com.innovation.chengzhangriji.http.BabyResponse;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteButton;
import com.innovation.chengzhangriji.ui.widget.CuteEditText;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.ui.widget.JoinAdapter;
import com.orhanobut.logger.Logger;

public class JoinActivity extends BaseActivity implements CuteToolbar.OnClickCuteToolbarListener, AdapterView.OnItemClickListener, View.OnTouchListener, View.OnClickListener {

    private static final String[] list = new String[]{"爸爸", "妈妈", "爷爷", "奶奶", "姥爷", "姥姥"};

    private String mSearchPhone;

    private JoinAdapter mJoinAdapter;

    private RecyclerView mRecyclerView;

    private CuteButton mButtonJoin;

    private TextInputLayout mTextInputLayout;

    private CuteEditText mInputName;

    private ListPopupWindow lpw;

    private ImageView mImageEmpty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSearchPhone = getIntent().getStringExtra("searchPhone");
        setupLayout();
        requestSearchAllBaby();
    }

    @Override
    public void onClickLeft() {
        finish();
    }

    @Override
    public void onClickRight() {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String item = list[position];
        mInputName.setText(item);
        lpw.dismiss();
    }

    @Override
    public void onClick(final View v) {
        if (v.getId() == R.id.button_join) {
            LoginInfo loginInfo = Config.getLoginInfo(this);
            if (loginInfo == null) {
                return;
            }
            String phone = loginInfo.getPhone();
            String token = loginInfo.getToken().getAccessToken();
            int babyID = mJoinAdapter.getJoinBabyID();
            String role = mInputName.getText().toString();
            if (TextUtils.isEmpty(role)) {
                tipShow("请输入称谓");
                return;
            }
            Client.requestJoin(this, phone, token, babyID, role, new ResponseHandler() {

                @Override
                public void onStart() {
                    showProgressDialog(null, null);
                }

                @Override
                public void onInnovationSuccess(JsonElement value) {
                    if (value.getAsInt() == 1) {
                        tipShow("申请成功！坐待对方验证吧！");
                        Intent intent = new Intent(JoinActivity.this, HomeActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        tipShow("未知的错误");
                    }
                }

                @Override
                public void onChZhRJFailure(String value) {
                    tipShow(value);
                }

                @Override
                public void onInnovationFinish() {
                    dismissProgressDialog();
                }

                @Override
                public void onInnovationExceptionFinish() {
                    dismissProgressDialog();
                }
            }, networkUnavailableSampleImpl());
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        final int DRAWABLE_RIGHT = 2;
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (event.getRawX() >= (mInputName.getRight() - mInputName.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                lpw.show();
                return true;
            }
        }
        return false;
    }

    private void setupLayout() {
        setContentView(R.layout.activity_join);
        CuteToolbar cuteToolbar = (CuteToolbar) findViewById(R.id.toolbar);
        cuteToolbar.setOnClickCuteToolbarListener(this);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(layoutManager);
        mJoinAdapter = new JoinAdapter();
        mRecyclerView.setAdapter(mJoinAdapter);
        mButtonJoin = (CuteButton) findViewById(R.id.button_join);
        mTextInputLayout = (TextInputLayout) findViewById(R.id.text_input_layout_name);
        mTextInputLayout.setHint("您是宝贝的?");
        CuteTextView textPhone = (CuteTextView) findViewById(R.id.text_phone);
        textPhone.setText("手机号: " + mSearchPhone);
        mInputName = (CuteEditText) findViewById(R.id.text_input_name);
        mImageEmpty = (ImageView) findViewById(R.id.image_empty);

        lpw = new ListPopupWindow(this);
        lpw.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list));
        lpw.setAnchorView(mInputName);
        lpw.setModal(true);
        lpw.setOnItemClickListener(this);
        mInputName.setOnTouchListener(this);
        mButtonJoin.setOnClickListener(this);

    }

    private void requestSearchAllBaby() {
        LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        Client.requestSearchAllBaby(this, phone, token, mSearchPhone, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                AllBabyResponse response = get(value.toString(), AllBabyResponse.class);
                if (response == null || response.getData().length == 0) {
                    mImageEmpty.setVisibility(View.VISIBLE);
                } else {
                    mRecyclerView.setVisibility(View.VISIBLE);
                    mButtonJoin.setVisibility(View.VISIBLE);
                    mTextInputLayout.setVisibility(View.VISIBLE);
                    BabyResponse[] babyResponses = response.getData();
                    mJoinAdapter.setBabyResponses(babyResponses);
                    mJoinAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onChZhRJFailure(String value) {
                mImageEmpty.setVisibility(View.VISIBLE);
            }

            @Override
            public void onInnovationFinish() {
                dismissProgressDialog();
            }

            @Override
            public void onInnovationExceptionFinish() {
                dismissProgressDialog();
            }

        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {
                dismissProgressDialog();
            }
        });
    }

}
